package cards.controller;

import java.util.Objects;

import cards.dao.UserDao;
import cards.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cards.service.RegisterService;
import cards.util.HostHolder;

/**
 * 个人简介接口
 * 
 * @author xiezhiping
 *
 */
@Controller
public class ProfileController {
	
	private static final Logger logger = LoggerFactory.getLogger(ProfileController.class);
	
	@Autowired
	private UserDao userDao;

	@Autowired
	private HostHolder hostHolder;

	@Autowired
	RegisterService registerService;

	@RequestMapping(path = "/profile/{id}", method = RequestMethod.GET)
	public String displayProfileById(@PathVariable Long id, Model model) {
		// user是该profile所属的用户
		User user = userDao.getUserById(id);
		logger.warn("[displayMyProfile] display profile, username:{}",user.getUsername());
		// other_user是当前登录的用户
		User otherUser=hostHolder.getUser();

		if (Objects.equals(user.getId(), otherUser.getId()))
		{
			model.addAttribute("user", otherUser);
			model.addAttribute("otherUser", user);
			model.addAttribute("switch", Objects.equals(user.getId(), otherUser.getId()));
			return "modifyprofile";
		}
		else
		{
			model.addAttribute("user", otherUser);
			model.addAttribute("otherUser", user);
			model.addAttribute("switch", Objects.equals(user.getId(), otherUser.getId()));
			return "profile";
		}

	}

	@RequestMapping(path = "/profile/{id}", method = RequestMethod.POST)
	public String modifyProfileById(@PathVariable Long id, @RequestParam("password") String password,
									  @RequestParam("introduction") String introduction,
									  @RequestParam("nickname") String nickname, @RequestParam("gender") int gender,
									  @RequestParam("phoneNumber") String phoneNumber, Model model) {
		// user是该profile所属的用户
		User user = userDao.getUserById(id);
		logger.warn("[modifyProfileById] modify profile, username:{}",user.getUsername());
		// other_user是当前登录的用户
		User otherUser=hostHolder.getUser();
		if (Objects.equals(user.getId(), otherUser.getId()))
		{
			model.addAttribute("user", otherUser);
			model.addAttribute("otherUser", user);
			model.addAttribute("switch", Objects.equals(user.getId(), otherUser.getId()));
		}
		return registerService.modify(id, password, introduction, nickname, gender, phoneNumber);
	}

	

}
